package com.zbu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbu.reggie.dto.DishDto;
import com.zbu.reggie.entity.Dish;
import com.zbu.reggie.entity.DishFlavor;
import com.zbu.reggie.mapper.DishMapper;
import com.zbu.reggie.service.DishFlavorService;
import com.zbu.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishSeriviceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    //新增菜品
    //同时插入菜品对应的口味数据 操作两个表 dish dish_flavor
    @Transactional//涉及2个表 进行事务管理
    @Override
    public void saveWithFlavor(DishDto dishDto) {

        //保存菜品的基本信息到 菜品表 dish
        this.save(dishDto);
        Long dishId = dishDto.getId();
        //保存菜品的口味数据到 口味表

        List<DishFlavor> flavors = dishDto.getFlavors();
        //设置dish_flavor表中的dishId
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());//重新转成list

        dishFlavorService.saveBatch(flavors);//批量保存

    }

    //查询菜品信息和对应的口味信息
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        //该菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(wrapper);

        dishDto.setFlavors(flavors);
        return dishDto;
    }

    //更新菜品信息和对应的口味信息
    @Transactional
    @Override
    public void updateWithFlavor(DishDto dishDto) {

        //更新dish的基本信息
        this.updateById(dishDto);

        //清除当前口味数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(wrapper);
        //添加当前口味数据

        List<DishFlavor> flavors = dishDto.getFlavors();

        //设置dish_flavor表中的dishId
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());//重新转成list

        dishFlavorService.saveBatch(flavors);

    }


}
